//var fs = require('fs')
var express = require('express')
var Student = require('./students.js')
//创建一个路由容器
var router = express.Router()
//使用容器
//进去主界面，渲染数据
router.get('/students', function (req, res) {
    Student.findAll(function (err, data) {
        if (err) {
            return res.status(500).send('Server error 500')
        } else {
            var newData = ['A', 'B', 'C', 'D']
            res.render('index.html', {
                newData: newData,
                students: JSON.parse(data).students
            })
        }
    })
})
//进入添加页面
router.get('/students/new', function (req, res) {
    res.render("new.html")
})
//提交添加的数据
router.post('/students/new', function (req, res) {
    Student.save(req.body, function (err) {
        if (err) {
            res.status(500).send('Fail error')
        }
        res.redirect('/students')
    })
})
//进入修改页面，并且传递将要修改的数据
router.get('/students/edit', function (req, res) {
    let getid = req.query.id
    console.log(getid);
    Student.findById(parseInt(getid), function (err, data) {
        if (err) {
            res.status(500).send("Error");
        } else {
            console.log(data);
            res.render('edit.html', {
                studentID: JSON.parse(data)
            })
        }
    })
})
//将修改好的数据，存放入文件中
router.post('/students/edit', function (req, res) {
    //{ id: 1, name: "wang", age: 'man', hobbies: 'nothing' }
    ///let {id,name,age,hobbies}=JSON.stringify(req.body)
    Student.updata(req.body, function (err, data) {
        if (err) {
            res.status(500).send('Fail error')
        }
        res.redirect('/students')
    })
})

router.get('/students/delete', function (req, res) {
    let Deleteid = parseInt(req.query.id);
    console.log('deleteid', Deleteid);
    Student.findById(Deleteid, function (err, data) {
        if (err) {
            res.status(500).send('Serveing Error');
        } else {
            console.log(data);
            var deledata = data;
            Student.delete(JSON.parse(deledata), function (err) {
                if (err) {
                    res.send('Write failed')
                } else {
                    res.redirect('/students')
                }
            })
        }
    })

})

module.exports = router;
